package com.ztom.offer.v2;

import java.util.HashMap;
import java.util.Map;

/**
 * 重建二叉树
 * <p>
 * https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof/
 *
 * @author ZhangTao
 */
public class Code05BuildTree {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    private Map<Integer, Integer> indexMap;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        int n = preorder.length;
        // 记录中序遍历每个节点的 index
        indexMap = new HashMap<>();
        for (int i = 0; i < n; i++) {
            indexMap.put(inorder[i], i);
        }
        return buildTree(preorder, inorder, 0, n - 1, 0, n - 1);
    }

    private TreeNode buildTree(int[] preorder, int[] inorder, int pl, int pr, int il, int ir) {
        if (pl > pr) {
            return null;
        }
        // root 节点就是先序的第一个
        int rp = pl;
        // 找到 root 在中序的 index
        int ri = indexMap.get(preorder[rp]);

        // 先序 pl, [pl + 1, pl + ln], [pl + ln + 1, pr]
        // 中序 [il, ri - 1], ri, [ri + 1, ir]
        TreeNode root = new TreeNode(preorder[rp]);
        // 左子树节点个数
        int ln = ri - il;
        root.left = buildTree(preorder, inorder, pl + 1, pl + ln, il, ri - 1);
        // 右子树节点个数
        int rn = ir - ri;
        root.right = buildTree(preorder, inorder, pl + ln + 1, pr, ri + 1, ir);
        return root;
    }
}
